﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using CommonSearchModule;
using System.Runtime.Serialization.Formatters.Binary;
using System.Configuration;
namespace ReadFile.WebService
{
    /// <summary>
    /// ReadFile 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class ReadFileIndex : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }


        /// <summary>
        /// 根据条件获取指定的索引
        /// </summary>
        /// <param name="module"></param>
        /// <param name="keyword"></param>
        /// <param name="categoryName"></param>
        /// <param name="propertyName"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [WebMethod]
        public byte[] ReadLocalFile(int module, string keyword, string categoryName, string propertyName, int page, int pagesize)
        {
            string _keyword = (keyword ?? string.Empty).Trim();
            string _categoryName = (categoryName ?? string.Empty).Trim();
            string _propertyName = propertyName;

            SearchResult result = GetDataFromIndex(module, new QueryTerm { KeyWord = _keyword, CategoryName = _categoryName, PropertyName = _propertyName, PageSize = pagesize, PageIndex = page });
            return ObjectToByteArray(result);
        }

        #region 类型转换
        byte[] ObjectToByteArray(object o)
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            bf.Serialize(ms, o);
            return ms.ToArray();
        }

        object ByteArrayToObject(byte[] ba)
        {
            MemoryStream ms = new MemoryStream(ba);
            BinaryFormatter bf = new BinaryFormatter();
            return bf.Deserialize(ms);
        }
        #endregion

        #region 获取索引
        /// <summary>
        /// 从索引文件中重到数据，根据关键字
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        protected virtual SearchResult GetDataFromIndex(int module, QueryTerm queryTerm)
        {
            QueryTerm term = new QueryTerm
            {
                KeyWord = queryTerm.KeyWord,
                PageIndex = queryTerm.PageSize,
                CategoryName = queryTerm.CategoryName,
                PropertyName = queryTerm.PropertyName,
                PageSize = 10,
            };

            string path;
            switch ((SearchModule)module)
            {
                case SearchModule.Ask:
                    path = this.GetIndexPath(ConfigurationManager.AppSettings["Ask_IndexDocumentsPath"]);
                    break;
                case SearchModule.Fudao:
                    path = this.GetIndexPath(ConfigurationManager.AppSettings["CourseRequirement_IndexDocumentsPath"]);
                    break;
                case SearchModule.Item:
                    path = this.GetIndexPath(ConfigurationManager.AppSettings["Res_Item_IndexDocumentsPath"]);
                    break;
                case SearchModule.JiaoAn:
                    path = this.GetIndexPath(ConfigurationManager.AppSettings["JiaoAn_IndexDocumentsPath"]);
                    break;
                case SearchModule.ShiTi:
                    path = this.GetIndexPath(ConfigurationManager.AppSettings["ShiJuan_IndexDocumentsPath"]);
                    break;
                default:
                    path = string.Empty;
                    break;
            }

            Search searcher = new Search(path, term);
            return searcher.GetSearchResult();
        }

        /// <summary>
        /// 调用WIN API方法
        /// 非托管资源
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="def"></param>
        /// <param name="retVal"></param>
        /// <param name="size"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        /// <summary>
        /// 得到索引文件路径
        /// </summary>
        /// <param name="configPath"></param>
        /// <returns></returns>
        protected string GetIndexPath(string configPath)
        {
            StringBuilder sbPath = new StringBuilder(500);
            GetPrivateProfileString("Index", "Path", "", sbPath, 500, configPath);

            return sbPath.ToString();
        }
        #endregion

    }
}
